<template>
  <div class="page-controller">
    <category-tree @node-click="handleNodeClick" />
    <!-- 查询条件区 -->
    <div class="page-form">
      <FISearchForm
        class="page-form__query"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        :searchNum="getHasSearchValues(state.query, 3, ['category'])"
        :excludeValues="['category']"
        v-model:form-value="state.query"
        :defaultFormNum="4"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="processDefinitionKey" label="流程编码">
            <FIInput v-model="state.query.processDefinitionKey" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="processDefinitionName" label="流程名称">
            <FIInput v-model="state.query.processDefinitionName" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="status" label="发布状态">
            <FISelect
              v-model="state.query.status"
              valueCustom="value"
              :options="[
                { value: '', label: '全部' },
                { value: 'draft', label: '未发布' },
                { value: 'published', label: '已发布' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="enable" label="启用状态">
            <FISelect
              v-model="state.query.enable"
              valueCustom="value"
              :options="[
                { value: '', label: '全部' },
                { value: 'Y', label: '启用' },
                { value: 'N', label: '停用' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <!-- 查询结果列表区 -->
      <FITable
        ref="tableRef"
        class="bpage-form__query margin-top20"
        title="流程信息"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="processDefinitionId"
        v-model:columns="columns"
        :isLoading="isTableLoading"
        :insertable="false"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @row-add-save="handleSave"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="handleAction"
      >
        <template #headerBtn>
          <FIButton border>在线设计</FIButton>
          <FIButton border @click="handleImportProcess" :info="selectCategoryData">导入流程</FIButton>
          <FIButton border @click="handleSetCategory">设置目录</FIButton>
          <!-- <FIPopconfirmBtn
            title="您确认要启用吗？"
            class="margin-left12"
            beforePopText="请选择一条数据"
            buttonText="启用"
            :btn-binds="{ border: true }"
            :isVisible="!!checkedRows.length"
            @confirm="handleEnable"
          /> -->
          <!-- <FIButton class="margin-left12" border @click="handleDisableEnable">停用</FIButton> -->
          <!-- <FIButton border>移至非审批流</FIButton> -->
          <!-- <FIPopconfirmBtn
            class="margin-left12"
            title="您是否确认删除选中数据吗？"
            beforePopText="请选择一条数据"
            buttonText="删除"
            :btn-binds="{ border: true }"
            :isVisible="!!checkedRows.length"
            @confirm="deleteRow"
          /> -->
          <FIButton class="margin-left12" border>部署</FIButton>
        </template>
        <template #Manage="{ scope }">
          <FIButton type="primary">编辑草稿版</FIButton>
          <FIButton type="primary">编辑最新发布版本</FIButton>
          <FIButton type="primary">查看全部发布版本</FIButton>
          <!-- <FIButton type="primary">更新</FIButton> -->
        </template>
      </FITable>
    </div>
    <ImportProcessModel
      :visible="showImportProcessModel"
      :info="selectCategoryData"
      @update:visible="(newValue) => (showImportProcessModel = newValue)"
      @save-ok="handleSaveImportProcessModel"
    />
    <SetCategoryModel
      :visible="showSetCategory"
      :info="selectCategoryData"
      @update:visible="(newValue) => (showSetCategory = newValue)"
      @confirm="handleSaveSetCategory"
    />
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed } from 'vue'
import CategoryTree from '../components/CategoryTree.vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import ImportProcessModel from '../components/ImportProcessModel.vue'
import SetCategoryModel from '../components/SetCategoryModel.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage, useMessageBox } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, getHasSearchValues } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import FIIconInput from '@/components/FIIconInput.vue'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const searchWrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = route.name as string
const showSetCategory = ref(false)
const showImportProcessModel = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    processDefinitionKey: '', // 流程编码
    processDefinitionName: '', // 流程名称
    status: '', // 发布状态
    enable: '', // 启动状态
    category: '', // 目录id
    // dynamicParams: [],
    // orderbyParams: [],
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
const selectCategoryData = ref('')
// 表格列数据
const columns: Column[] = reactive([
  { label: '流程编码', prop: 'processDefinitionKey', align: 'center', width: '150' },
  { label: '流程名称', prop: 'processDefinitionName', editable: true, align: 'center', width: '150' },
  {
    label: '状态',
    prop: 'processStatus',
    align: 'center',
    width: '80',
    editType: 'select',
    editable: true,
    options: [
      { label: '', value: '' },
      { label: '未发布', value: 'draft' },
      { label: '已发布', value: 'published' },
    ],
  },
  {
    label: '启用状态',
    prop: 'enable',
    align: 'center',
    width: '100',
    editType: 'select',
    editable: true,
    options: [
      { label: '', value: '' },
      { label: '启用', value: 'Y' },
      { label: '停用', value: 'N' },
    ],
    editConfig: {
      // 编辑配置
      options: [
        { label: '启用', value: 'Y' },
        { label: '停用', value: 'N' },
      ],
      selectBinds: {
        // 下拉框绑定值
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  // {
  //   label: '流程分类',
  //   prop: 'processClass',
  //   align: 'center',
  //   width: '120',
  //   editType: 'select',
  //   options: [
  //     { label: '', value: '' },
  //     { label: '任务类', value: 'T' },
  //     { label: '通知类', value: 'N' },
  //   ],
  // },
  { label: '流程描述', editable: true, width: '150', prop: 'processDefinitionDescription' },
  { label: '停用原因', editable: false, prop: 'disableDesc' },
  // {
  //   label: '管理',
  //   prop: 'Manage',
  //   // width: 600,
  //   // editType: 'custom',
  //   // customSlot: 'action',
  //   actionConfig: [
  //     { label: '编辑草稿版', type: 'editDraft' },
  //     { label: '编辑最新发布版', type: 'editPublished' },
  //     { label: '查看全部发布版本', type: 'viewHistory' },
  //     { label: '更新', type: 'update' },
  //     { label: '复制', type: 'copy' },
  //   ],
  // },
  {
    label: '管理',
    prop: 'action',
    width: 200,
    actionConfig: [
      { label: '启用', type: 'enableY' },
      { label: '停用', type: 'enableN' },
      { label: '移至非审批流', type: 'moveToNoApproval' },
      { label: '删除', type: 'delete' },
      { label: '编辑草稿版', type: 'editDraft' },
      { label: '编辑最新发布版', type: 'editPublished' },
      { label: '查看全部发布版本', type: 'viewHistory' },
      // { label: '更新', type: 'update' },
      // { label: '复制', type: 'copy' },
    ],
  },
])
const handleAction = (item, rowData) => {
  console.log('handleEnable----', item, rowData)
  switch (item.type) {
    case 'enableY':
      handleEnableSatrt(rowData)
      break
    case 'enableN':
      handleDisableEnable(rowData)
      break
    case 'moveToNoApproval':
      handleMoveToNoApproval(rowData)
      break
    case 'delete':
      deleteRow(rowData)
      break
    // case 'editDraft':
    //   stopFn(rowData)
    //   break
    // case 'editPublished':
    //   restartFn(rowData)
    //   break
    //   case 'viewHistory':
    //   stopFn(rowData)
    //   break
    //   case 'update':
    //   stopFn(rowData)
    //   break
  }
}
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
const handleNodeClick = (data) => {
  console.log('---------data', data)
  selectCategoryData.value = data
  state.query.category = data.id
  searchFn()
}
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  console.log('---------api', apiUrl)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      console.log('res---------0001', res)
      if (res.data.success) {
        state.dataList = res.data.data.result
        console.log('res---------002', state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// table保存提交
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('save', route.name)
  checkedRows.value.forEach((item: any) => {
    item.processKey = item.processDefinitionKey
    item.processName = item.processDefinitionName
    item.description = item.processDefinitionDescription
    // item.processClass = item.processClass
  })
  console.log('api----', apiUrl)
  apiRequestPost(apiUrl, checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const handleImportProcess = () => {
  if (!selectCategoryData.value) {
    useMessage().warning('请至少选择一个目录')
    return
  }
  showImportProcessModel.value = true
}
// 导入流程成功
const handleSaveImportProcessModel = () => {
  searchFn()
}
const handleSaveSetCategory = (id) => {
  const arr = []
  checkedRows.value.forEach((item) => {
    let obj = {
      id: id,
      processKey: item.processDefinitionKey,
    }
    arr.push(obj)
  })
  apiRequestPost('/bpm-service/BpmProcessDef/updateCategory', arr)
    .then((res) => {
      if (res.data.success) {
        searchFn()
      } else {
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const handleSetCategory = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请至少选择一条数据')
    return
  }
  showSetCategory.value = true
}
// 启用流程定义 type: Y 启用 N 停用
const handleEnable = (type = 'Y', rowData, disableDescStr) => {
  // if (!checkedRows.value.length) {
  //   useMessage().warning('请选择一条数据')
  //   return
  // }
  rowData.enable = type
  rowData.disableDesc = disableDescStr
  rowData.processDefinitionId = rowData.processDefinitionId
  rowData.processKey = rowData.processDefinitionKey
  isTableLoading.value = true
  apiRequestPost('/bpm-service/BpmProcessDef/updateEnable', [rowData])
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success('更新成功')
        searchFn()
      } else {
        useMessage().success(res.data.message)
      }
    })
    .catch(() => {
      isTableLoading.value = false
    })
}
// const handleEnable = (type = 'Y', disableDescStr) => {
//   if (!checkedRows.value.length) {
//     useMessage().warning('请选择一条数据')
//     return
//   }
//   let arr = []
//   Array.isArray(checkedRows.value) &&
//     checkedRows.value.forEach((item: any) => {
//       let params = {
//         enable: type,
//         disableDesc: disableDescStr,
//         processDefinitionId: item.processDefinitionId,
//         processKey: item.processDefinitionKey,
//       }
//       arr.push(params)
//     })
//   let obj = checkedRows.value[0]
//   // let params = {
//   //   enable: type,
//   //   disableDesc: '',
//   //   processDefinitionId: obj.processDefinitionId,
//   //   processKey: obj.processDefinitionKey,
//   // }
//   isTableLoading.value = true
//   apiRequestPost('/bpm-service/BpmProcessDef/updateEnable', arr)
//     .then((res) => {
//       isTableLoading.value = false
//       if (res.data.success) {
//         useMessage().success('更新成功')
//         searchFn()
//       } else {
//         useMessage().success(res.data.message)
//       }
//     })
//     .catch((error: any) => {
//       isTableLoading.value = false
//     })
// }
// 启用流程定义
const handleEnableSatrt = (rowData) => {
  useMessageBox()
    .confirm('您确认要启用吗？', '启用')
    .then(() => {
      handleEnable('Y', rowData, '')
    })
}
// 停用流程定义
const handleDisableEnable = (rowData) => {
  useMessageBox()
    .prompt('请输入停用流程原因', '停用流程原因')
    .then(({ value }) => {
      handleEnable('N', rowData, value)
    })
    .catch(() => {})
}
// 移至非审批流
const handleMoveToNoApproval = (rowData) => {}
// 删除流程定义
const deleteRow = (rowData) => {
  let ids = [
    {
      processDefinitionId: rowData.processDefinitionId,
      processKey: rowData.processDefinitionKey,
      state: rowData.processStatus,
    },
  ]
  isTableLoading.value = true
  apiRequestPost('/bpm-service/BpmProcessDef/deleteProcessDef', ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success('删除成功')
        searchFn()
      }
    })
    .catch(() => {
      isTableLoading.value = false
    })
}

onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped>
.page-controller {
  width: 100%;
  display: flex;
  .page-form {
    flex: 1;
    margin: 0 20px;
    max-width: calc(100% - 280px);
    .page-form__query {
      width: 100%;
    }
  }
}
</style>
